package cn.b.sky.user.freemarker;

import freemarker.cache.TemplateLoader;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

/**
 * 
 * <strong>Title : HtmlTemplateLoader.java<br></strong>
 * <strong>Package : cn.b.sky.user.freemarker<br></strong>
 * <strong>Description : </strong>FreeMarker模板输出转义html,防止js脚本攻击<br> 
 * <strong>Create on : 2016-3-23 下午4:11:44<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class HtmlTemplateLoader implements TemplateLoader {

  private static final String HTML_ESCAPE_PREFIX = "<#escape x as x?html>";

  private static final String HTML_ESCAPE_SUFFIX = "</#escape>";

  private final TemplateLoader delegate;

  public HtmlTemplateLoader(TemplateLoader delegate) {
    this.delegate = delegate;
  }

  @Override
  public void closeTemplateSource(Object templateSource) throws IOException {
    delegate.closeTemplateSource(templateSource);

  }

  @Override
  public Object findTemplateSource(String name) throws IOException {
    return delegate.findTemplateSource(name);
  }

  @Override
  public long getLastModified(Object templateSource) {
    return delegate.getLastModified(templateSource);
  }

  @Override
  public Reader getReader(Object templateSource, String encoding) throws IOException {
    Reader reader = delegate.getReader(templateSource, encoding);
    String templateText = IOUtils.toString(reader);
    return new StringReader(HTML_ESCAPE_PREFIX + templateText + HTML_ESCAPE_SUFFIX);
  }

}
